package cn.kent.service;

import cn.kent.common.Message;
import cn.kent.common.MessageType;
import cn.kent.util.DateUtil;
import cn.kent.util.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Iterator;

public class SendNewsToAllService implements Runnable {

    @Override
    public void run() {
        while (true) {
            System.out.print("请输入服务器需要推送的新闻/消息(exit退出)： ");
            String news = Utility.readString(100);
            if ("exit".equals(news)) {
                break;
            }
            Message message = new Message();
            message.setContent(news);
            message.setSender("Server");
            message.setMsgType(MessageType.MESSAGE_TO_ALL_MES);
            message.setSendTime(DateUtil.getNowDateStr());
            System.out.println("服务器推送消息给所有人说：" + news);

            // 遍历所有的集合，进行消息分发
            HashMap<String, ServerConnectClientThread> map = ManageClientThreads.getMap();
            Iterator<String> iterator = map.keySet().iterator();
            while (iterator.hasNext()) {
                String onLineUserId = iterator.next();
                try {
                    ObjectOutputStream oos = new ObjectOutputStream(map.get(onLineUserId).getSocket().getOutputStream());
                    oos.writeObject(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
